package net.chasing.androidbaseconfig.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import net.chasing.androidbaseconfig.util.thread.ComparableRunnable;
import net.chasing.androidbaseconfig.util.thread.ThreadPoolUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ObjectCacheUtil {

    public static final String FILENAME = "objectCache";


    /**
     * desc:保存对象
     *
     * @param obj 要保存的对象，只能保存实现了serializable的对象
     */
    public static void saveObject(Context context, String key, Object obj) {
        if (context == null) return;
        ThreadPoolUtils.getInstance().execute(new ComparableRunnable() {
            @Override
            public void run() {
                ByteArrayOutputStream bos = null;
                ObjectOutputStream os = null;
                try {
                    // 保存对象
                    SharedPreferences.Editor sharedata = context.getSharedPreferences(FILENAME, Context.MODE_PRIVATE).edit();
                    //先将序列化结果写到byte缓存中，其实就分配一个内存空间
                    bos = new ByteArrayOutputStream();
                    os = new ObjectOutputStream(bos);
                    //将对象序列化写入byte缓存
                    os.writeObject(obj);
                    //将序列化的数据转为16进制保存
                    String bytesToHexString = bytesToHexString(bos.toByteArray());
                    //保存该16进制数组

                    sharedata.putString(key, bytesToHexString);
                    sharedata.apply();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (bos != null)
                            bos.close();
                        if (os != null)
                            os.close();
                    } catch (Exception ignored) {
                    }
                }
            }
        });
    }

    /**
     * desc:将数组转为16进制
     */
    private static String bytesToHexString(byte[] bArray) {
        if (bArray == null) {
            return null;
        }
        if (bArray.length == 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder(bArray.length);
        String sTemp;
        for (byte b : bArray) {
            sTemp = Integer.toHexString(0xFF & b);
            if (sTemp.length() < 2)
                sb.append(0);
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }

    public static Object readObject(Context context, String key) {
        return readObject(context, key, null);
    }

    /**
     * desc:获取保存的Object对象
     */
    public static Object readObject(Context context, String key, Object value) {
        if (context == null) return value;
        try {
            SharedPreferences sharedata = context.getSharedPreferences(FILENAME, Context.MODE_PRIVATE);
            if (sharedata.contains(key)) {
                String string = sharedata.getString(key, "");
                if (TextUtils.isEmpty(string)) {
                    return value;
                } else {
                    //将16进制的数据转为数组，准备反序列化
                    byte[] stringToBytes = StringToBytes(string);
                    ByteArrayInputStream bis = new ByteArrayInputStream(stringToBytes);
                    ObjectInputStream is = new ObjectInputStream(bis);
                    //返回反序列化得到的对象
                    return is.readObject();
                }
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        //所有异常返回null
        return value;
    }

    public static void remove(Context context, String key) {
        if (context == null) return;
        SharedPreferences sharedata = context.getSharedPreferences(FILENAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sharedata.edit();
        edit.remove(key);
        edit.apply();
    }

    public static void clear(Context context) {
        if (context == null) return;
        SharedPreferences sharedata = context.getSharedPreferences(FILENAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sharedata.edit();
        edit.clear();
        edit.apply();
    }

    /*
     * 把16进制字符串转换成字节数组 @param hex @return
     */
    private static byte[] StringToBytes(String hex) {
        int len = (hex.length() / 2);
        byte[] result = new byte[len];
        char[] achar = hex.toCharArray();
        for (int i = 0; i < len; i++) {
            int pos = i * 2;
            result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
        }
        return result;
    }

    private static byte toByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }


}
